<!DOCTYPE html>
<html>
  <head>
    <title>Mac推流端</title>
  </head>
  <body>
    <h3>本地预览</h3>
    <video
      id="localVideo"
      autoplay
      muted
      playsinline
      width="320"
      height="240"
    ></video>
    <p id="status">准备推流...</p>
    <p id="trackStatus">视频轨道状态：未初始化</p>
    <!-- 添加按钮手动启用轨道（应急用） -->
    <button onclick="enableVideoTrack()">启用视频轨道</button>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();
      const localVideo = document.getElementById("localVideo");
      const status = document.getElementById("status");
      const trackStatus = document.getElementById("trackStatus");
      let localStream;
      let videoTrack; // 单独保存视频轨道引用
      let peerConnection;
      let viewerId = null;

      async function startBroadcast() {
        try {
          // 1. 强制请求摄像头权限，确保轨道激活
          localStream = await navigator.mediaDevices.getUserMedia({
            video: {
              width: 640,
              height: 480,
              frameRate: 15,
              // 明确要求非静音轨道
              advanced: [{ muted: false }],
            },
            audio: false,
          });
          localVideo.srcObject = localStream;

          // 2. 获取视频轨道并监控状态
          videoTrack = localStream.getVideoTracks()[0];
          if (!videoTrack) {
            throw new Error("未检测到视频轨道，请检查摄像头");
          }
          updateTrackStatus(); // 初始状态更新

          // 3. 监听轨道状态变化（关键）
          videoTrack.onmute = () => {
            console.warn("视频轨道被静音/禁用！");
            updateTrackStatus();
            // 尝试自动恢复
            if (videoTrack.muted) {
              videoTrack.muted = false; // 取消静音
            }
          };
          videoTrack.onunmute = () => {
            console.log("视频轨道已启用");
            updateTrackStatus();
          };
          videoTrack.onended = () => {
            console.error("视频轨道已结束！");
            updateTrackStatus();
            // 尝试重新获取摄像头
            restartCamera();
          };

          status.textContent = "等待观众连接...";
          socket.emit("broadcaster");
        } catch (err) {
          console.error("初始化失败:", err);
          status.textContent = `错误: ${err.message}`;
          return;
        }
      }

      // 手动启用轨道的函数
      function enableVideoTrack() {
        if (videoTrack) {
          videoTrack.muted = false; // 取消静音
          if (videoTrack.readyState === "ended") {
            restartCamera(); // 轨道已结束则重启摄像头
          }
          updateTrackStatus();
        }
      }

      // 重新获取摄像头（轨道结束时调用）
      async function restartCamera() {
        status.textContent = "尝试重新获取摄像头...";
        if (localStream) {
          localStream.getTracks().forEach((track) => track.stop()); // 停止旧轨道
        }
        // 重新请求媒体流
        localStream = await navigator.mediaDevices.getUserMedia({
          video: { width: 640, height: 480 },
          audio: false,
        });
        localVideo.srcObject = localStream;
        videoTrack = localStream.getVideoTracks()[0]; // 更新轨道引用
        // 重新添加到连接
        if (peerConnection) {
          peerConnection.getSenders().forEach((sender) => {
            if (sender.track && sender.track.kind === "video") {
              sender.replaceTrack(videoTrack); // 替换旧轨道
            }
          });
        }
        updateTrackStatus();
      }

      // 更新轨道状态显示
      function updateTrackStatus() {
        if (!videoTrack) return;
        trackStatus.textContent = `视频轨道状态：
        激活=${videoTrack.enabled}，
        静音=${videoTrack.muted}，
        状态=${videoTrack.readyState}
      `;
      }

      // 观众连接时处理
      socket.on("viewer-connected", async (id) => {
        viewerId = id;
        status.textContent = `观众已连接: ${viewerId}`;

        peerConnection = new RTCPeerConnection({
          iceServers: [
            { urls: "stun:stun.l.google.com:19302" },
            { urls: "stun:stun1.l.google.com:19302" },
            // 添加TURN服务器
            {
              urls: "turn:turn.anyfirewall.com:443?transport=tcp",
              username: "webrtc",
              credential: "webrtc",
            },
          ],
        });

        // 关键：添加轨道时确保已激活
        if (videoTrack && videoTrack.enabled && !videoTrack.muted) {
          const sender = peerConnection.addTrack(videoTrack, localStream);
          console.log("添加视频轨道到连接，状态:", videoTrack.readyState);
          peerConnection.getSenders().forEach((sender) => {
            console.log(
              "发送轨道状态:",
              sender.track.readyState,
              "是否激活:",
              sender.track.enabled
            );
          });
          peerConnection.getSenders().forEach((sender) => {
            console.log(
              "发送轨道状态:",
              sender.track.readyState,
              "是否激活:",
              sender.track.enabled
            );
          });
        } else {
          console.error("无法添加轨道：轨道未激活或被静音");
          status.textContent = "错误：视频轨道未激活，请检查摄像头";
          return;
        }

        // 其他信令逻辑（保持不变）
        peerConnection.onicecandidate = (event) => {
          if (event.candidate && viewerId) {
            socket.emit("signal", {
              target: viewerId,
              type: "ice",
              candidate: event.candidate,
            });
          }
        };

        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        socket.emit("signal", {
          target: viewerId,
          type: "offer",
          sdp: offer,
        });
      });

      // 处理观众信令（保持不变）
      socket.on("signal", async (data) => {
        if (!viewerId || data.from !== viewerId) return;

        if (data.type === "answer") {
          await peerConnection.setRemoteDescription(
            new RTCSessionDescription(data.sdp)
          );
        } else if (data.type === "ice") {
          await peerConnection.addIceCandidate(
            new RTCIceCandidate(data.candidate)
          );
        }
      });

      window.onload = startBroadcast;
    </script>
  </body>
</html>
